import React, { useEffect, useState, Fragment, useMemo } from 'react';
import {
    HcpTable,
    HcpTimerFilterSelect,
    HcpTableTooltip,
    HcpTableFilterBar,
    HcpProjectSelect,
    HcpOrgFilterSelect,
    HcpColumnsFilter,
    HcpTipModal,
    hcpConfirm,
    isAuthorized,
    Authorized,
    HcpOperationTooltip
} from '@/components';
import { Button, Select, Input, message, Form, Space, Popover } from 'antd';
import request from '@/utils/request';
import hcpcmdb from '@/data/hcpcmdb';
import hcpalarm from '@/data/hcpalarm';
import alarmStatus from '../alarm.status';
import hcpUtils from '@/utils/hcpUtils';
import { getQueryParams } from './utils'

const AlarmInfo = ({ history, alarmType, resourceUuid }) => {
    const [form] = Form.useForm();
    const [properties, setProperties] = useState({});
    const [selectInput, setSelectInput] = useState('alarmDesc');

    const onSTChange = (value) => {
        setSelectInput(value);
        form.setFieldsValue({
            alarmDesc: undefined,
        });
    };
    const onFinish = () => {
        let values = form.getFieldValue();
        setProperties({ ...properties, ...values });
    };

    // 定义清空限制条件的函数
    const resetFrom = () => {
        setSelectInput('alarmDesc');
    };

    const handleFilters = (type, item) => {
        let _item = item.map((v) => {
            return v.value;
        });
        setProperties((properties) => {
            return { ...properties, [type]: _item };
        });
    };

    const columns = [
        {
            title: '告警设备/ID',
            dataIndex: 'instanceName',
            fixed: 'left',
            alwaysShow: true,
            render: (text, record, index) => (
                <HcpTableTooltip
                    label="ID"
                    showValue={text}
                    copyValue={record.instanceId}
                    idValue={record.instanceId}
                    onClick={() =>  window.open(`${window.location.origin}/portal/alarm/info/assets/detail/${record._id.replaceAll('.', '~')}`, '_blank')}
                />
            ),
        },
        {
            title: '告警对象',
            dataIndex: 'resourceName',
            isShow: true,
        },
        {
            title: '品牌',
            dataIndex: 'brand',
            isShow: true,
        },
        {
            title: '告警类型',
            dataIndex: 'alarmType',
            isShow: true,
            render: (text, record) => alarmStatus.status(text),
        },
        {
            title: '智能告警',
            dataIndex: 'isIntellect',
            isShow: window.ENVP?.alarmIntellect,
            render: (text) => alarmStatus.intellectStatus(text || 0),
        },
        {
            title: '告警内容',
            dataIndex: 'alarmDesc',
            isShow: true,
        },
        {
            title: (
                <HcpColumnsFilter
                    name="级别"
                    dataSource={alarmStatus.infoRankFileter}
                    handleChange={(item) => handleFilters('alarmLvl', item)}
                />
            ),
            dataIndex: 'alarmLvl',
            isShow: true,
            render: (text) => {
                return (
                    <Fragment>
                        <span className={`alarm-level level-${text}`} />
                        <span>{alarmStatus.status(text)}</span>
                    </Fragment>
                );
            },
        },
        {
            title: '告警状态',
            dataIndex: 'alarmStatus',
            isShow: true,
            render: (text) => alarmStatus.alarmStatusFun(text),
        },
        {
            title: '确认状态',
            dataIndex: 'confirmStatus',
            isShow: true,
            render: (text) => alarmStatus.confirmStatus(text),
        },
        {
            title: '发生时间',
            dataIndex: 'alarmTime',
            isShow: true,
            type: 'time',
        },
        {
            title: '持续时间',
            dataIndex: 'alarmDuration',
            isShow: true,
            render: (text, record) => {
                let diff = Math.abs(Date.now() - record?.alarmTime);
                record.alarmDurationTime = hcpUtils.formatTime(diff);
                return hcpUtils.formatTime(diff);
            }
        },
    ];
    const [loading, setLoading] = useState(false);
    const [tableData, setTableData] = useState([]);
    const [isInitParam, setIsInitParam] = useState(true);

    const [pagination, setPagination] = useState({
        current: 1,
        pageSize: 10,
        total: 0,
    });

    const initParam = { alarmType: [alarmType], instanceName: resourceUuid };
    const getTableData = async (params = { current: 1, pageSize: 10 }) => {
        if(!resourceUuid) {
            message.warning("未获取到设备名称！");
            return;
        }
        setLoading(true);
        const res = await request({
            ...hcpalarm.queryAlarmInfo,
            data: {
                ...getQueryParams({ ...initParam, ...properties }),
                skip: (params.current - 1) * params.pageSize,
                limit: params.pageSize,
            },
        });
        setLoading(false);
        if (res && res.monitor) {
            setPagination({
                ...params,
                total: res.totalNum,
            });
            res.monitor.map((i, index) => (i.key = index));
            let data = Array.from(new Set(res.monitor))
            setTableData(data);
        } else {
            setTableData([]);
        }
    };

    useEffect(() => {
        setIsInitParam(false);
        onFinish();
    }, []);

    useEffect(() => {
        if (!isInitParam) {
            getTableData();
        }
    }, [properties]);

    const handleTableChange = (e) => {
        getTableData(e);
    };

    // 重置表头筛选
    const [colReset, setColReset] = useState(0);
    const handleRefresh = () => {
        setColReset(colReset + 1);
    };
    return (

        <div>
            <Space className="hcp_toolbar">
                <Button onClick={handleRefresh}>刷新</Button>
            </Space>
            <section className="hcp__search__collapse hcp_search_bar">
                <section className="hcp__form">
                    <HcpTableFilterBar
                        form={form}
                        resetClick={resetFrom}
                        onSearch={onFinish}
                        items={[
                            {
                                field: 'alarmDesc',
                                component: (
                                    <Input.Group
                                        compact
                                        style={{
                                            display: 'flex',
                                        }}
                                    >
                                        <Form.Item noStyle>
                                            <Select
                                                style={{
                                                    width: '110px',
                                                }}
                                                defaultValue="alarmDesc"
                                                onChange={
                                                    onSTChange
                                                }
                                                getPopupContainer={(
                                                    triggerNode
                                                ) =>
                                                    triggerNode.parentElement
                                                }
                                            >
                                                <Select.Option value="alarmDesc">
                                                    告警内容
                                                </Select.Option>
                                            </Select>
                                        </Form.Item>
                                        {selectInput ==
                                            'alarmDesc' ? (
                                            <Form.Item
                                                style={{
                                                    width: '130px',
                                                }}
                                                hidden={
                                                    selectInput !=
                                                    'alarmDesc'
                                                }
                                                name="alarmDesc"
                                            >
                                                <Input
                                                    placeholder="模糊搜索"
                                                    maxLength={
                                                        100
                                                    }
                                                />
                                            </Form.Item>
                                        ) : (
                                            ''
                                        )}
                                    </Input.Group>
                                ),
                            },
                            {
                                field: 'timer',
                                superStyle: { width: '212px' },
                                component: (
                                    <HcpTimerFilterSelect style={{ width: '212px' }} />
                                ),
                            },
                        ]}
                    />
                </section>
            </section>
            <HcpTable
                rowKey={(record) => record._id}
                colReset={colReset}
                columns={columns}
                loading={loading}
                handleFilters={handleFilters}
                dataSource={tableData}
                scroll={{ x: '100%' }}
                pagination={{
                    showSizeChanger: true,
                    showTotal: (total, range) => (
                        <span className="table-total-num">
                            共{total}条记录
                        </span>
                    ),
                    showQuickJumper: {
                        goButton: (
                            <Button
                                style={{ margin: '0 10px' }}
                            >
                                确定
                            </Button>
                        ),
                    },
                    ...pagination,
                }}
                onChange={handleTableChange}
                hideSetting
            />
        </div>
    );
};
export default AlarmInfo;
